package 对象及变量的并发访问;


class HasSelfPrivateNumTwo{
	private int num=0;
	synchronized public void addI(String username)//加上synchronied就不会发生"非线程安全"的问题
	{try {
		
			if(username.equals("a"))
			{
				num=100;
				System.out.println("a set over!");
				Thread.sleep(2000);
				
			}
			else
			{
				num=200;
				System.out.println("b set over!");
			}
			System.out.println(username+" num="+num);
		}catch(InterruptedException e)
			{
					e.printStackTrace();
			}
	}
}
class ThreadAAs extends Thread{
	private  HasSelfPrivateNumTwo numRef;
	public ThreadAAs(HasSelfPrivateNumTwo numRef2)
	{
		super();
		this.numRef=numRef2;
		
	}
	public void run()
	{
		super.run();
		numRef.addI("a");
	}
}
class ThreadBBs extends Thread{
	private HasSelfPrivateNumTwo numRef;
	public ThreadBBs(HasSelfPrivateNumTwo numRef2)
	{
		super();
		this.numRef=numRef2;
		
	}
	public void run()
	{
		super.run();
		numRef.addI("b");
	}
}

public class Test2_5 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		HasSelfPrivateNumTwo	numRef1=new HasSelfPrivateNumTwo();
		HasSelfPrivateNumTwo	numRef2=new HasSelfPrivateNumTwo();

		ThreadAAs athread=new ThreadAAs(numRef1);
		athread.start();
		ThreadBBs bthread=new ThreadBBs(numRef2);
		bthread.start();
		//该程序中使用了两个线程分别访问同一个类的两种不同实例的相同名称的同步方法，效果是以异步的方式运行的。创建两个对象，产生了两个锁，
		//所以运行结果是异步的，打印效果是先打印b,然后打印a.
		
		

	}

}
